package com.fancy.cc.security.util;

import com.fancy.cc.common.exception.NotLoginException;
import com.fancy.cc.security.domain.AdminUserDetails;

import java.util.Objects;

/**
 * @author yongxin
 * @Title: 当前用户信息
 * @Package
 * @Description:
 * @date 2021/9/110:57
 */
public class CurrentUserUtil {
    /**
     * 保存用户对象的ThreadLocal  在拦截器操作 添加、删除相关用户数据
     */
    private static final ThreadLocal<AdminUserDetails> userThreadLocal = new ThreadLocal<>();

    /**
     * 添加当前登录用户方法  在拦截器方法执行前调用设置获取用户
     *
     * @param user
     */
    public static void addCurrentUser(AdminUserDetails user) {
        userThreadLocal.set(user);
    }

    /**
     * 获取当前登录用户方法
     */
    public static AdminUserDetails getCurrentUser() {
        return userThreadLocal.get();
    }

    /**
     * 获取当前登录用户方法
     *
     * @return
     */
    public static Long getMerchantId() {
        AdminUserDetails details = userThreadLocal.get();
        if (Objects.isNull(details)) {
            throw new NotLoginException();
        }
        return details.getMerchantId();
    }

    /**
     * 删除当前登录用户方法  在拦截器方法执行后 移除当前用户对象
     */
    public static void remove() {
        userThreadLocal.remove();
    }

    public static Long getId() {
        AdminUserDetails details = userThreadLocal.get();
        if (Objects.isNull(details)) {
            throw new NotLoginException();
        }
        return details.getId();
    }

    public static Integer getRole() {
        AdminUserDetails details = userThreadLocal.get();
        if (Objects.isNull(details)) {
            throw new NotLoginException();
        }
        return details.getRole();
    }
}
